﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Linq;
using System.Globalization;
using AllTalk.Data;

namespace AllTalk
{
    public class FriendViewModel : ViewModelBase
    {
        private Friend _friend;
        
        public string Name
        {
            get
            {
                if (_friend.Name == null || _friend.Name.Length <= 0)
                {
                    return _friend.Email.Substring(0,_friend.Email.IndexOf('@'));
                }
                return _friend.Name;
            }
        }
      
        public string Email
        {
            get
            {
                return _friend.Email;
            }
        }

        public string StatusMessage
        {
            get
            {
                return _friend.StatusMessage;
            }
        }
  
        public string Presence
        {
            get
            {
                return _friend.Presence.ToString();
            }
        }

        public ImageSource Image
        {
            get
            {
                return _friend.Picture.Source;
            }
        }

        public FriendViewModel() {}

        internal FriendViewModel(Friend friend)
        {
            _friend = friend;
            _friend.PresenceChanged += new EventHandler<PresenceChangedEventArgs>(Friend_PresenceChanged);
            _friend.PictureLoaded += new EventHandler<EventArgs>(Friend_PictureLoaded);
        }

        private void Friend_PresenceChanged(object sender, PresenceChangedEventArgs eventArgs)
        {
            if (eventArgs.NewValue == AllTalk.Presence.Unavailable)
            {
                _friend.PresenceChanged -= new EventHandler<PresenceChangedEventArgs>(Friend_PresenceChanged);
                App.ViewModel.FriendViewModels.Remove(this);
                // TODO: Remove model
            }
            NotifyPropertyChanged("Status");
        }

        private void Friend_PictureLoaded(object sender, EventArgs eventArgs)
        {
            NotifyPropertyChanged("Image");
        }
    }

}